/**
 * 测试题model
 */
'use strict'
import {fetchTimus, complete} from "../services/testService";

export default {

  namespace: 'quiz',

  state: {
    txList: [{name: '听力模块', typeId: '1'}, {name: '阅读模块', typeId: '2'}],//所有题型
    currTx: 'ydmk',                     //当前测试模块
    currIndex: 0,                        //当前题目的下标
    quizList: [],           //所有题目 typeId 题型Id question 问题 answer 回答
    myAnswer: [],           //考生回答出来的答案
    startDate: '',          //开始考试时间
  },

  subscriptions: {},

  effects: {
    * fetchTimus({body}, {call, put}) {  //取题目
      //先清空题目缓存,再拉取
      yield put({type: 'kaishi', payload: []});

      const {data = []} = yield call(_ => fetchTimus(body));
      yield put({type: 'kaishi', payload: data});
    },
    * complete({testType, history}, {call, put, select}) {  //交卷
      const {myAnswer, startDate} = yield select(stores => stores.quiz);
      const body = {testDetails: myAnswer, tmSource: {type: testType}, startDate};

      const {data = []} = yield call(_ => complete(body));
      yield put({type: 'quizList', payload: data});

      //回调成功跳到,推荐老师页面
      if (testType === 2) {//周测
        yield put({type: 'study/testResults'});
        history.push('/study');
      } else {//首测
        history.push('/book/firstTest/tuijian');
      }
    },
  },

  reducers: {
    kaishi(state = {}, action) {
      return {...state, quizList: action.payload, currIndex: 0, startDate: new Date(), myAnswer: []};
    },
    answer(state = {}, {answer, xtIndex, timuId}) {//回答问题
      const {myAnswer = []} = state || {};
      //去除老答案
      const newMyAnsWer = myAnswer.filter(({timuId: t}) => t !== timuId);
      newMyAnsWer.push({timuId, stuAnswer: answer});
      return {...state, myAnswer: newMyAnsWer};
    },
    next(state = {}) {//下一题
      let {currIndex, quizList} = state;
      if (currIndex < quizList.length - 1) currIndex++;
      return {...state, currIndex};
    },
  },
};
